<?php
//未完成，仅供参考
define('_SESSION_EXP',3600);
define('_MEMCACHE_HOST','192.168.3.2');
define('_MEMCACHE_PORT','11211');

class MemcacheSession{
    static $_sessionSavePath;
    static $_sessionName;
    static $_memcacheObj;

    public function __construct(){
        if(!class_exists('Memcache') || !function_exists('memcache_connect'))
            die('Can not load Memcache extension!');
        if(!empty(self::$_memcacheObj) && is_object(self::$_memcacheObj))
            return    false;

        self::$_memcacheObj= new Memcache;
       
        if(!self::$_memcacheObj->connect(_MEMCACHE_HOST,_MEMCACHE_PORT))
            die('Can not connect to memcache host:'._MEMCACHE_HOST.',prot:'._MEMCACHE_PORT);
        return(true);
    }

    public function open($pSavePath='',$pSessionName=''){
        self::$_sessionSavePath=$pSavePath;
        self::$_sessionName=$pSessionName;
        return true;
    }

    public function close(){
        return true;
    }

    public function read($pSessionID=''){
        $data=self::$_memcacheObj->get($pSessionID);
       
        if(!empty($data)){
            return    $data;
        }else{
            $ret=self::$_memcacheObj->set($pSessionID,'',0,_SESSION_EXP);
            if(true!=$ret){
                die('session id $pSessionID init failed');
                return    false;
            }
            return    true;
        }
           
    }

    public function write($pSessionID='',$pData=''){
        $ret=self::$_memcacheObj->replace($pSessionID,$pData,0,_SESSION_EXP);
        if(true!=$ret){
            die('session id $pSessionID save data failed!');
            return    false;
        }
        return    true;
    }

    public function destroy($pSessionID=''){
        self::write($pSessionID);
        return    false;
    }

    public function gc(){
        return    true;
    }

    public function init(){
        $domain='.a.com';
       
        ini_set('session.use_trans_sid',0);
        ini_set('session_gc_maxlifetime',_SESSION_EXP);
		
        ini_set('session.use_cookies',1);
        ini_set('session.cookie_path','/');
        ini_set('session.save_path','/tmp');

        ini_set('session.cookie_domain',$domain);

        session_module_name('user');

        session_set_save_handler(array('MemcacheSession','open'),array('MemcacheSession','close'),array('MemcacheSession','read'),array('MemcacheSession','write'),array('MemcacheSession','destroy'),array('MemcacheSession','gc'));

        session_start();
        return    true;


    }
}